<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\meituan\service;

use app\meituan\model\MeituanOrderModel;
use app\portal\model\PortalPostModel;
use think\facade\Db;

class MeituanOrderImportService
{
    public $OrderUrl = 'https://runion.meituan.com/api/orderList';
    public $createUrl = 'https://runion.meituan.com/generateLink';
    public $key = '4155db3f20ebd153c04c96147ebfe6cc';
    public $script = '0f4d3fe8e2f607da2b771a3a55c156d7';
    public $script_notify = 'gb8cwkj53x';


    /**
     * 生成自主短连接
     * @param string $flag
     * @return array|string
     * User: sunc
     * Date: 2021/7/7 16:32
     */
    public function createUrl($flag = '')
    {
        if (empty($flag)) {
            return ['code' => 500, 'msg' => '参数为空!'];
        }
        $secret = cmf_get_option('meituan');
        if (empty($secret)) {
            return ['code' => 500, 'msg' => 'appKey为空!'];
        }
        $sendData = [
            'key' => $this->key,
            'actId' => '2',
            'sid' => $flag,
            'linkType' => 1,
        ];
        $sign = $this->genSign($sendData);
        $sendData['sign'] = $sign;
        $sendData = http_build_query($sendData);
        $res = cmf_curl_get($this->createUrl . '?' . $sendData);
        if ($res['status'] == 0) {
            $code = $this->shortUrl($res['data']);
            return ['code' => 500, 'msg' => $res['des'], 'url' => $code];
        }
        return ['code' => 500, 'msg' => $res['des']];
    }

    /**
     * 由长连接生成短链接操作
     *
     * 算法描述：使用6个字符来表示短链接，我们使用ASCII字符中的'a'-'z','0'-'9','A'-'Z'，共计62个字符做为集合。
     *           每个字符有62种状态，六个字符就可以表示62^6（56800235584），那么如何得到这六个字符，
     *           具体描述如下：
     *        1. 对传入的长URL+设置key值 进行Md5，得到一个32位的字符串(32 字符十六进制数)，即16的32次方；
     *        2. 将这32位分成四份，每一份8个字符，将其视作16进制串与0x3fffffff(30位1)与操作, 即超过30位的忽略处理；
     *        3. 这30位分成6段, 每5个一组，算出其整数值，然后映射到我们准备的62个字符中, 依次进行获得一个6位的短链接地址。
     *
     */
    public function getShortUrl($url)
    {
        $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        $key = "jiuqiwan";
        $urlhash = md5($key . $url);
        $len = strlen($urlhash);
        #将加密后的串分成4段，每段4字节，对每段进行计算，一共可以生成四组短连接
        for ($i = 0; $i < 4; $i++) {
            $urlhash_piece = substr($urlhash, $i * $len / 4, $len / 4);
            #将分段的位与0x3fffffff做位与，0x3fffffff表示二进制数的30个1，即30位以后的加密串都归零
            $hex = hexdec($urlhash_piece) & 0x3fffffff; #此处需要用到hexdec()将16进制字符串转为10进制数值型，否则运算会不正常
//            $short_url = $domain . "t.php/";
            $short_url = '';
            #生成6位短连接
            for ($j = 0; $j < 6; $j++) {
                #将得到的值与0x0000003d,3d为61，即charset的坐标最大值
                $short_url .= $charset[$hex & 0x0000003d];
                #循环完以后将hex右移5位
                $hex = $hex >> 5;
            }
            $short_url_list[] = $short_url;
        }
        return $short_url_list;
    }

    /**
     * 获取短连接
     * User: sunc
     * Date: 2021/7/7 16:28
     */
    public function shortUrl($url)
    {
        $ret = $this->getShortUrl($url);
        $user = ['long_url' => $url, 'short_url_code' => $ret[0], 'create_time' => time()];
        Db::name('long_short_url')->insert($user);
        $sortUrl = 'http://taoke.ccfancy.com/t.php/' . $ret[0];
        return $sortUrl;
    }

    /**
     * 导出订单
     * @param array $params
     * @return bool
     * @throws \Exception
     * User: sunc
     * Date: 2021/7/7 16:51
     */
    public function importOrder($params = [])
    {
        $secret = cmf_get_option('meituan');
        if (empty($secret)) {
            return false;
        }
        $sendData = [
            'key' => $this->key,
            'type' => '4',
            'ts' => (string)time(),
            'startTime' => (string)(time() - 86400 * 7),
            'endTime' => (string)time(),
            'page' => '1',
            'limit' => '100',
            'queryTimeType' => '1',
        ];
        $sign = $this->genSign($sendData);
        $sendData['sign'] = $sign;
        $sendData = http_build_query($sendData);
        $res = cmf_curl_get($this->OrderUrl . '?' . $sendData);
        $res = json_decode($res, true);
        if (!empty($res['dataList'])) {
            $meiOrder = new MeituanOrderModel();
            $meiOrder->saveAll($res['dataList']);
        }
        return true;
    }

    // php
    public function genSign($params = [])
    {
        $secret = cmf_get_option('meituan');
        if (empty($secret)) {
            return false;
        }
        unset($params["sign"]);
        ksort($params);
        $str = $this->script; // $secret为分配的密钥
        foreach ($params as $key => $value) {
            $str .= $key . $value;
        }
        $str .= $this->script;
        $sign = md5($str);
        return $sign;
    }

    /**
     * 文章查询
     * @param      $filter
     * @param bool $isPage
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function adminPostList($filter, $isPage = false)
    {

        $field = 'a.*,u.user_login,u.user_nickname,u.user_email';

        $portalPostModel = new PortalPostModel();
        $articlesQuery = $portalPostModel->alias('a');
        $articlesQuery->join('user u', 'a.user_id = u.id');

        $category = empty($filter['category']) ? 0 : intval($filter['category']);
        if (!empty($category)) {
            $articlesQuery->join('portal_category_post b', 'a.id = b.post_id');
            $field = 'a.*,b.id AS post_category_id,b.list_order,b.category_id,u.user_login,u.user_nickname,u.user_email';
        }

        $articles = $articlesQuery->field($field)
            ->where('a.create_time', '>=', 0)
            ->where('a.delete_time', 0)
            ->where(function (Query $query) use ($filter, $isPage) {

                $category = empty($filter['category']) ? 0 : intval($filter['category']);
                if (!empty($category)) {
                    $query->where('b.category_id', $category);
                }

                $startTime = empty($filter['start_time']) ? 0 : strtotime($filter['start_time']);
                $endTime = empty($filter['end_time']) ? 0 : strtotime($filter['end_time']);
                if (!empty($startTime)) {
                    $query->where('a.published_time', '>=', $startTime);
                }
                if (!empty($endTime)) {
                    $query->where('a.published_time', '<=', $endTime);
                }

                $keyword = empty($filter['keyword']) ? '' : $filter['keyword'];
                if (!empty($keyword)) {
                    $query->where('a.post_title', 'like', "%$keyword%");
                }

                if ($isPage) {
                    $query->where('a.post_type', 2);
                } else {
                    $query->where('a.post_type', 1);
                }
            })
            ->order('update_time', 'DESC')
            ->paginate(10);

        return $articles;
    }


}
